package jp.dodododo.reloadable.servlet.impl;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import jp.dodododo.reloadable.servlet.ServletContextListenerWrapper;
import jp.dodododo.reloadable.util.InitializeUtils;

public class ServletContextListenerWrapperImpl implements ServletContextListenerWrapper {

	private String targetClass;

	private ServletContextListener target;

	public ServletContextListenerWrapperImpl(String targetClass) {
		this.targetClass = targetClass;
	}

	public void initTarget(ServletContextEvent event) throws Exception {
		ClassLoader cl = Thread.currentThread().getContextClassLoader();
		Class<?> clazz = Class.forName(targetClass, true, cl);
		target = ServletContextListener.class.cast(clazz.newInstance());

		long start = System.currentTimeMillis();
		target.contextInitialized(event);
		long end = System.currentTimeMillis();
		InitializeUtils.initializeInfoLog(targetClass, start, end);
	}

	public void destroyTarget(ServletContextEvent event) {
		try {
			if (target != null) {
				target.contextDestroyed(event);
			}
		} finally {
			target = null;
		}
	}
}
